﻿using System;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;
using System.Net;

using LowLevelGraphics.Extractors;
using LowLevelGraphics.Drawing;
using CustomDrawnFileDialog;
using OpenFileDialog = CustomDrawnFileDialog.CustomFileDialog;

using ImageRecognition2.Action;
using ImageRecognition2.Forms;
using ImageRecognition2.FilterSets;

using LowLevelGraphics;
using LowLevelGraphics.VideoFormats;
using LowLevelGraphics.Forms;
using LowLevelGraphics.Histograms;
using LowLevelGraphics.Filter;
using LowLevelGraphics.ColorSpaces;
using SelectablePictureBox = LowLevelGraphics.CustomControls.SelectablePictureBox;

using LowLevelGraphics.Analysis;
using LowLevelGraphics.ImageAcquiring;
using LowLevelGraphics.Types.Interval;
using LowLevelGraphics.Drawing.FloodFillModes;
using LowLevelGraphics.Extensions;
using LowLevelGraphics.ImageFormats;

using Histogram = LowLevelGraphics.Histograms.Histogram;

using ImageRecognition2.MouseImageTools;

using dcraw;

namespace ImageRecognition2
{
    public delegate Bitmap BitmapDelegate(Bitmap bmp);
    public delegate Bitmap UnsafeBitmapDelegate(UnsafeBitmap bmp);

    /// <summary>
    /// 
    /// </summary>
    public partial class Form1 : Form
    {
        private static FormTypeCommand formTypeCommand = null;

        protected List<Color> m_aColorProbe = new List<Color>();

        private PictureBox m_PictureBox = null;
        private Panel panel = null;

        internal AVI m_AVI = new AVI();

        public static Dictionary<IFilter, string> m_aFilter = new Dictionary<IFilter, string>();

        private bool m_bCutImage = false;
        //private bool m_bMouseDown = false;
        private Point m_ptStart = new Point(-1, -1);
        private Point m_ptEnd = new Point(-1, -1);
        private Rectangle m_CutRectangle = Rectangle.Empty;
        private static FormCapture formCapture = null;

        //Bitmap m_Bitmap = null;
        private List<ColorRect> m_aColorRect = new List<ColorRect>();
        private delegate UnsafeBitmap VoidDelegate(UnsafeBitmap bmp);
        private delegate void VoidDelegateIBitmap(IBitmap bmp);
        private delegate void VoidDelegateApplication();
        private delegate void VoidDelegateInt(int nValue);
        private delegate bool BoolDelegate(Bitmap bmp);
        private delegate bool BoolDelegateByte(Bitmap bmp, byte _byte);
        private delegate bool BoolDelegateSByte(Bitmap bmp, sbyte _sbyte);
        private delegate bool BoolWeight(Bitmap bmp, int nWeight);
        private delegate bool BoolDelegateByteArray(Bitmap bmp, byte[,] _aByteArray);
        private delegate void VoidDelegateByteArray(Bitmap bmp, byte[,] _aByteArray);
        private delegate void VoidDelegateParams(Bitmap bmp, params object[] args);
        private delegate void VoidDelegateNonParameters();

        private bool m_bUseStandardFileDialog = true;

        private static Form formFilterPreferences = null;

        //private string m_sFileName = @"c:\palme.jpg";

        /// <summary>
        /// Initializes a new instance of the <see cref="Form1"/> class.
        /// </summary>
        public Form1()
        {
            InitializeComponent();
            Initialize();

            //string filename = @"C:\Program Files (x86)\Adobe\Adobe Photoshop CS5.1\Beispiele\Türen.dng";
            //DcRawState state = new DcRawState();
            //state.inFilename = filename;
            //state.ifp = new RawStream(filename);

            //Identifier id = new Identifier(state);
            //id.identify(state.ifp);

            //&a.LoadRaw();
        }

        /// <summary>
        /// Initialize
        /// </summary>
        private void Initialize()
        {
            this.AllowDrop = true;
            this.DragDrop += new DragEventHandler(Form1_DragDrop);
            this.DragOver += new DragEventHandler(Form1_DragOver);
            this.DragEnter += new DragEventHandler(Form1_DragEnter);
            Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
            InitializeSettings();

            MainFormSingleton.Create(this);

            //Show the testcontrols only on my computer
            bool bComputerNameIsTest = true ? true : false;
            ShowTestControls(bComputerNameIsTest);

            this.toolStripComboBox1.Size = new Size(this.toolStripComboBox1.Width + 450, this.toolStripComboBox1.Height);

            FormChild child = GuiHelper.CreateNewChild();

            //SelectionTool a = new SelectionTool(child.pictureBox1);
            //a.Activate();

            InitializeEventHandlers();

            this.openedWindowsToolStripMenuItem.DropDownOpening += delegate(object sender, EventArgs e)
            {
                this.openedWindowsToolStripMenuItem.DropDownItems.Clear();
                foreach (Form form in this.MdiChildren)
                {
                    ToolStripItem item = this.openedWindowsToolStripMenuItem.DropDownItems.Add(form.Text);
                    item.Click += delegate(object senderTemp, EventArgs eTemp)
                    {
                        form.Activate();
                    };
                }
            };
        }

        void Application_ApplicationExit(object sender, EventArgs e)
        {
            m_AVI.Close();
        }


        /// <summary>
        /// Handles the DragOver event of the Form1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DragEventArgs"/> instance containing the event data.</param>
        void Form1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

        /// <summary>
        /// Handles the DragEnter event of the Form1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DragEventArgs"/> instance containing the event data.</param>
        void Form1_DragEnter(object sender, DragEventArgs e)
        {
            // Check if the Dataformat of the data can be accepted
            // (we only accept file drops from Explorer, etc.)
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy; // Okay              
            }
            else
            {
                e.Effect = DragDropEffects.None; // Unknown data, ignore it
            }
        }

        /// <summary>
        /// Handles the DragDrop event of the FormChild control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DragEventArgs"/> instance containing the event data.</param>
        void Form1_DragDrop(object sender, DragEventArgs e)
        {
            // Handle FileDrop data.
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                // Assign the file names to a string array, in 
                // case the user has selected multiple files.
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                try
                {
                    foreach (string sPic in files)
                    {
                        FormChild child = GuiHelper.CreateNewChild();
                        child.LoadPicture(sPic);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }

        /// <summary>
        /// Initializes the settings.
        /// </summary>
        private void InitializeSettings()
        {
            GuiHelper.m_bOpenNewChildOnAction = this.openNewWindowAfterActionToolStripMenuItem.Checked = Properties.Settings.Default.bOpenWindowAfterAction;

            this.tileHorizontalAfterActionHorizontalTeilenToolStripMenuItem.Checked = Properties.Settings.Default.bTileWindowHorizontalAfterAction;
            this.tileVerticalAfterActionStripMenuItem.Checked = Properties.Settings.Default.bTileWindowVerticalAfterAction;

            this.m_bUseStandardFileDialog = this.defaultFileDialogToolStripMenuItem.Checked = Properties.Settings.Default.bUseStandardDialog;
        }

        /// <summary>
        /// Saves the settings.
        /// </summary>
        private void SaveSettings()
        {
            Properties.Settings.Default.bOpenWindowAfterAction = this.openNewWindowAfterActionToolStripMenuItem.Checked;
            Properties.Settings.Default.bTileWindowHorizontalAfterAction = tileHorizontalAfterActionHorizontalTeilenToolStripMenuItem.Checked;
            Properties.Settings.Default.bTileWindowVerticalAfterAction = this.tileVerticalAfterActionStripMenuItem.Checked;
            Properties.Settings.Default.bUseStandardDialog = this.defaultFileDialogToolStripMenuItem.Checked;
            Properties.Settings.Default.Save();
        }

        /// <summary>
        /// Initialize all event handlers
        /// </summary>
        private void InitializeEventHandlers()
        {
            GuiHelper.SetEventHandler(saveToolStripMenuItem, new ActionSave());
            GuiHelper.SetEventHandler(toolStripButtonZoomIn, new ActionZoom(true));
            GuiHelper.SetEventHandler(toolStripButtonZoomOut, new ActionZoom(false));
            GuiHelper.SetEventHandler(toolStripButtonZoomReset, new ActionZoom(100.0f));

            //initialize Toolbar items
            GuiHelper.SetEventHandler(toolStripButtonAverageGray, new ActionCreateAverageGrayImage(true));
            GuiHelper.SetEventHandler(toolStripButtonBlackPoints, new ActionColorDistance(Definitions.Black));
            GuiHelper.SetEventHandler(toolStripButtonWhitePoints, new ActionColorDistance(Definitions.White));
            GuiHelper.SetEventHandler(toolStripButtonGrayPoints, new ActionColorDistance(Definitions.Gray));
            GuiHelper.SetEventHandler(toolStripButtonWhitePoint, new ActionExecuteDelegate(new VoidDelegate(new WhiteColorBalance(WHITECOLORBALANCE_MODE.USE_YCBCR_MODE).Execute)));
            ActionTwoSourceFilters newActionTwoSourceFilters = new ActionTwoSourceFilters(new NAnd());

            GuiHelper.SetEventHandler(reexecutePreviousFilterToolStripMenuItem, new ActionExecuteLastExecutedFilter());

            GuiHelper.SetEventHandler(mode1ToolStripMenuItem, new ActionFloodFill(new FloodFill3()));

            //ImageLayout
            GuiHelper.SetEventHandler(noneToolStripMenuItem, new ActionImageLayout(ImageLayout.None));
            GuiHelper.SetEventHandler(centerToolStripMenuItem, new ActionImageLayout(ImageLayout.Center));
            GuiHelper.SetEventHandler(stretchToolStripMenuItem, new ActionImageLayout(ImageLayout.Stretch));
            GuiHelper.SetEventHandler(tileToolStripMenuItem, new ActionImageLayout(ImageLayout.Tile));
            GuiHelper.SetEventHandler(zoomToolStripMenuItem, new ActionImageLayout(ImageLayout.Zoom));

            //InterpolationMode
            //Nearest neighbour will use no interpolation mode
            GuiHelper.SetEventHandler(noneToolStripMenuItem1, new ActionInterpolationMode(InterpolationMode.NearestNeighbor));
            GuiHelper.SetEventHandler(nearestNeighbourToolStripMenuItem, new ActionInterpolationMode(InterpolationMode.NearestNeighbor));
            GuiHelper.SetEventHandler(bicubicToolStripMenuItem, new ActionInterpolationMode(InterpolationMode.Bicubic));
            GuiHelper.SetEventHandler(bilinearToolStripMenuItem, new ActionInterpolationMode(InterpolationMode.Bilinear));
            GuiHelper.SetEventHandler(highQualityBicubicToolStripMenuItem, new ActionInterpolationMode(InterpolationMode.HighQualityBicubic));
            GuiHelper.SetEventHandler(highQualityBilinearToolStripMenuItem, new ActionInterpolationMode(InterpolationMode.HighQualityBilinear));
            GuiHelper.SetEventHandler(lowToolStripMenuItem, new ActionInterpolationMode(InterpolationMode.Low));
            GuiHelper.SetEventHandler(highToolStripMenuItem, new ActionInterpolationMode(InterpolationMode.HighQualityBilinear));
            GuiHelper.SetEventHandler(defaultToolStripMenuItem, new ActionInterpolationMode(InterpolationMode.Default));


            //Initialize Context Menu handlers and corresponding toolbar drop down buttons
            GuiHelper.SetEventHandler(nandToolStripMenuItem1, newActionTwoSourceFilters);
            GuiHelper.SetEventHandler(andToolStripMenuItem2, newActionTwoSourceFilters);

            ActionTwoSourceFilters newActionTwoSourceFilters1 = new ActionTwoSourceFilters(new And());
            GuiHelper.SetEventHandler(andToolStripMenuItem1, newActionTwoSourceFilters1);
            GuiHelper.SetEventHandler(andToolStripMenuItem2, newActionTwoSourceFilters1);

            ActionTwoSourceFilters newActionTwoSourceFilters2 = new ActionTwoSourceFilters(new XOR());
            GuiHelper.SetEventHandler(xorToolStripMenuItem, newActionTwoSourceFilters2);
            GuiHelper.SetEventHandler(xORToolStripMenuItem2, newActionTwoSourceFilters2);

            ActionTwoSourceFilters newActionTwoSourceFilters3 = new ActionTwoSourceFilters(new OR());
            GuiHelper.SetEventHandler(orToolStripMenuItem1, newActionTwoSourceFilters3);
            GuiHelper.SetEventHandler(oRToolStripMenuItem2, newActionTwoSourceFilters3);

            ActionTwoSourceFilters newActionTwoSourceFilters4 = new ActionTwoSourceFilters(new Divide());
            GuiHelper.SetEventHandler(divideToolStripMenuItem, newActionTwoSourceFilters4);
            GuiHelper.SetEventHandler(divideToolStripMenuItem2, newActionTwoSourceFilters4);

            ActionTwoSourceFilters newActionTowSourceFiltersModulo = new ActionTwoSourceFilters(new Modulo());
            GuiHelper.SetEventHandler(moduloToolStripMenuItem, newActionTowSourceFiltersModulo);

            ActionTwoSourceFilters newActionTwoSourceFilters5 = new ActionTwoSourceFilters(new XOR());
            GuiHelper.SetEventHandler(xorToolStripMenuItem, newActionTwoSourceFilters5);
            GuiHelper.SetEventHandler(xORToolStripMenuItem2, newActionTwoSourceFilters5);

            ActionTwoSourceFilters newActionTwoSourceFilters6 = new ActionTwoSourceFilters(new Multiplication());
            GuiHelper.SetEventHandler(multiplicateToolStripMenuItem, newActionTwoSourceFilters6);
            GuiHelper.SetEventHandler(multiplicateToolStripMenuItem2, newActionTwoSourceFilters6);

            ActionTwoSourceFilters newActionTwoSourceFilters7 = new ActionTwoSourceFilters(new XNOR());
            GuiHelper.SetEventHandler(xNorToolStripMenuItem, newActionTwoSourceFilters7);
            GuiHelper.SetEventHandler(xNorToolStripMenuItem2, newActionTwoSourceFilters7);

            ActionTwoSourceFilters newActionTwoSourceFilters8 = new ActionTwoSourceFilters(new Average());
            GuiHelper.SetEventHandler(averageToolStripMenuItem, newActionTwoSourceFilters8);
            GuiHelper.SetEventHandler(averageToolStripMenuItem2, newActionTwoSourceFilters8);

            ActionTwoSourceFilters newActionTwoSourceFilters9 = new ActionTwoSourceFilters(new Add());
            GuiHelper.SetEventHandler(addToolStripMenuItem, newActionTwoSourceFilters9);
            GuiHelper.SetEventHandler(addToolStripMenuItem2, newActionTwoSourceFilters9);

            ActionTwoSourceFilters newActionTwoSourceFilters10 = new ActionTwoSourceFilters(new Sub());
            GuiHelper.SetEventHandler(subToolStripMenuItem, newActionTwoSourceFilters10);
            GuiHelper.SetEventHandler(subToolStripMenuItem2, newActionTwoSourceFilters10);

            ActionTwoSourceFilters newActionTwoSourceFiltersSameColorValues = new ActionTwoSourceFilters(new SameColorValues());
            GuiHelper.SetEventHandler(sameColorValuesToolStripMenuItem, newActionTwoSourceFiltersSameColorValues);

            ActionTwoSourceFilters newActionTwoSourceFiltersDepthmap = new ActionTwoSourceFilters(new DepthMap());
            GuiHelper.SetEventHandler(depthmapToolStripMenuItem, newActionTwoSourceFiltersDepthmap);

            GuiHelper.SetEventHandler(quitToolStripMenuItem, new ActionExecuteNonFilterDelegate(delegate(object sender, EventArgs e) { Application.Exit(); }));
            // Handles the reload item click. this is used to reload a picture
            GuiHelper.SetEventHandler(reloadToolStripMenuItem,
                new ActionExecuteNonFilterDelegate(
                    delegate(object sender, EventArgs e)
                    {
                        Reload();
                    }));

            //GuiHelper.SetEventHandler(quitToolStripMenuItem, new ActionExecuteNonFilterDelegate(delegate(object sender, EventArgs e) { Application.Exit(); }));

            //windows

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            Application.ApplicationExit += delegate(object sender, EventArgs e)
            {
                SaveSettings();
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            quitToolStripMenuItem.Click += delegate(object sender, EventArgs e) { Application.Exit(); };

            /// <summary>
            /// </summary>
            /// This is used to open a new child if needed and load a picture 
            /// <param name="sender"></param>
            /// <param name="e"></param>
            openToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                //GuiHelper.SetEventHandler(openToolStripMenuItem, new ActionExecuteNonFilterDelegate(new VoidDelegateNonParameters(OpenNewPicture)));
                OpenNewPicture();
            };

            openFromUrlToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                //GuiHelper.SetEventHandler(openFromUrlToolStripMenuItem, new ActionExecuteNonFilterDelegate(new VoidDelegateNonParameters(OpenFromUrl)));
                OpenFromUrl();
            };

            openVideoToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                //GuiHelper.SetEventHandler(openVideoToolStripMenuItem, new ActionExecuteNonFilterDelegate(new VoidDelegateNonParameters(OpenVideo)));
                OpenVideo();
            };

            openLastLoadedToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                //GuiHelper.SetEventHandler(openLastLoadedToolStripMenuItem, new ActionExecuteNonFilterDelegate(new VoidDelegateNonParameters(Reload)));
                Reload();
            };

            openLastSavedToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
            };

            examplesToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            originalSizeToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                //GuiHelper.SetEventHandler(originalSizeToolStripMenuItem, new ActionExecuteNonFilterDelegate(new VoidDelegateNonParameters(OriginalSize)));
                Helper.OriginalSize();
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            createHistogramToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Histogram();
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            hueProfilToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                HueProfile();
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            tileVerticalAfterActionStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", tileVerticalAfterActionStripMenuItem.Name, "tile vertical after action"));
                tileVerticalAfterActionStripMenuItem.Checked = !tileVerticalAfterActionStripMenuItem.Checked;
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            tileHorizontalAfterActionHorizontalTeilenToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", tileHorizontalAfterActionHorizontalTeilenToolStripMenuItem.Name, "tile horizontal after action"));
                tileHorizontalAfterActionHorizontalTeilenToolStripMenuItem.Checked = !tileVerticalAfterActionStripMenuItem.Checked;
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            maskeToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", maskeToolStripMenuItem.Name, "Mask"));
                FormMask formMask = new FormMask();
                formMask.MdiParent = this;
                formMask.Show();
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            childsToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", childsToolStripMenuItem.Name, "childs"));
                FormChildList formChild = new FormChildList();
                formChild.MdiParent = this;
                formChild.Show();
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            neuesFensterToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", neuesFensterToolStripMenuItem.Name, "childs"));
                GuiHelper.CreateNewChild();
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            newWindowopenCopyToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                //GuiHelper.SetEventHandler(newWindowopenCopyToolStripMenuItem, new ActionExecuteNonFilterDelegate(new VoidDelegateNonParameters(NewWindowOpenCopy)));
                Helper.NewWindowOpenCopy();
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></par
            /// <param name="e"></param>
            newWindowlastLoadedToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                //GuiHelper.SetEventHandler(newWindowlastLoadedToolStripMenuItem, new ActionExecuteNonFilterDelegate(new VoidDelegateNonParameters(NewWindowLastLoaded)));
                Helper.NewWindowLastLoaded();
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            cascadeToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", cascadeToolStripMenuItem.Name, "cascade"));
                this.LayoutMdi(MdiLayout.Cascade);
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            iconsToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", iconsToolStripMenuItem.Name, "icons"));
                this.LayoutMdi(MdiLayout.ArrangeIcons);
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            tileHorizontalToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", tileHorizontalToolStripMenuItem.Name, "tile horizontal"));
                this.LayoutMdi(MdiLayout.TileHorizontal);
            };

            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            tileVerticalToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", tileVerticalToolStripMenuItem.Name, "tile vertical"));
                this.LayoutMdi(MdiLayout.TileVertical);
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            filterAnwendenAufToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", filterAnwendenAufToolStripMenuItem.Name, "use filter to..."));
                formFilterPreferences = new FormFilterPreferences();
                formFilterPreferences.ShowDialog();
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            pixelscannerToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", pixelscannerToolStripMenuItem.Name, "pixelscanner"));

                Form form = new FormPixelScanner((Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage);
                form.ShowDialog();
            };

            colorSamplesToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", colorSamplesToolStripMenuItem.Name, "colorsamples"));
                Form form = new FormColorSample();
                form.Show(this);
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            openNewWindowAfterActionToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", openNewWindowAfterActionToolStripMenuItem.Name, "open new window after action"));

                GuiHelper.m_bOpenNewChildOnAction = (openNewWindowAfterActionToolStripMenuItem.Checked = !openNewWindowAfterActionToolStripMenuItem.Checked);
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            copyToClipboardToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", copyToClipboardToolStripMenuItem.Name, "copy to clipboard"));
                Clipboard.SetData(DataFormats.Bitmap, MainFormSingleton.ActivePictureBox.BackgroundImage);
            };

            redoLastCommandToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", redoLastCommandToolStripMenuItem.Name, "redo last command"));

            };

            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            pasteFromClipboard.Click += delegate(object sender, EventArgs e)
            {
                //GuiHelper.SetEventHandler(pasteFromClipboard, new ActionExecuteNonFilterDelegate(new VoidDelegateNonParameters(ReadFromClipboard)));
                Helper.ReadFromClipboard();
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            automaticToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", automaticToolStripMenuItem.Name, "automatic"));
                automaticToolStripMenuItem.Checked = !automaticToolStripMenuItem.Checked;
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            quarterSizeToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", quarterSizeToolStripMenuItem.Name, "quarter size"));
                Size szDouble = new Size(MainFormSingleton.ActivePictureBox.BackgroundImage.Size.Width / 4, MainFormSingleton.ActivePictureBox.BackgroundImage.Size.Height / 4);

                Bitmap bitmap = BitmapFunctions.Resize((Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage, szDouble);
                MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap;
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            sizeToolStripMenuItem1.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", sizeToolStripMenuItem1.Name, "size double"));
                Size szDouble = new Size(MainFormSingleton.ActivePictureBox.BackgroundImage.Size.Width / 8, MainFormSingleton.ActivePictureBox.BackgroundImage.Size.Height / 8);

                Bitmap bitmap = BitmapFunctions.Resize((Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage, szDouble);
                MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap;
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            sizeToolStripMenuItem2.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", sizeToolStripMenuItem2.Name, "size double"));
                Size szDouble = new Size(MainFormSingleton.ActivePictureBox.BackgroundImage.Size.Width / 16, MainFormSingleton.ActivePictureBox.BackgroundImage.Size.Height / 16);

                Bitmap bitmap = BitmapFunctions.Resize((Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage, szDouble);
                MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap;
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            defaultFileDialogToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", defaultFileDialogToolStripMenuItem.Name, "use standard file dialog"));

                m_bUseStandardFileDialog = (defaultFileDialogToolStripMenuItem.Checked = !defaultFileDialogToolStripMenuItem.Checked);
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            brightnessGradientLeftRightToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", brightnessGradientLeftRightToolStripMenuItem.Name, "brightness profile (left->right)"));
                UnsafeBitmap _bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
                ShowProfile(_bitmap, "Brightness profile left->right");
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            doubleSizeToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", doubleSizeToolStripMenuItem.Name, "double size"));

                Size szDouble = new Size(MainFormSingleton.ActivePictureBox.BackgroundImage.Size.Width * 2, MainFormSingleton.ActivePictureBox.BackgroundImage.Size.Height * 2);

                Bitmap bitmap = BitmapFunctions.Resize((Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage, szDouble);
                MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap;
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            halfSizeToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", halfSizeToolStripMenuItem.Name, "half size"));

                Size szDouble = new Size(MainFormSingleton.ActivePictureBox.BackgroundImage.Size.Width / 2, MainFormSingleton.ActivePictureBox.BackgroundImage.Size.Height / 2);

                Bitmap bitmap = BitmapFunctions.Resize((Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage, szDouble);
                MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap;
            };

            /// <summary>
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            webcamCapturingDeviceToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", halfSizeToolStripMenuItem.Name, "webcam capturing device"));
                formCapture = new FormCapture();
                if (formCapture.ShowDialog() != DialogResult.OK) return;
                MainFormSingleton.ActivePictureBox.BackgroundImage = formCapture.Image;
            };

            /// <summary>
            /// 
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            scriptConsoleToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", halfSizeToolStripMenuItem.Name, "start script console (imagescriptconsole.exe)"));
                string sApplicationPath = string.Format(@"{0}\{1}", Application.StartupPath, "ImageScriptConsole.exe");
                Process.Start(sApplicationPath);
            };

            /// <summary>
            /// 
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            onlineToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", onlineToolStripMenuItem.Name, "search online pics"));
                FormOnlinePicSearch formOnlinePicSearch = new FormOnlinePicSearch();
                if (formOnlinePicSearch.ShowDialog() != DialogResult.OK) return;
                MainFormSingleton.ActivePictureBox.BackgroundImage = formOnlinePicSearch.Image;
                MainFormSingleton.ActivePictureBox.Invalidate();
            };

            /// <summary>
            /// 
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            screenshotToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", onlineToolStripMenuItem.Name, "screenshot"));
                FormScreenshot form = new FormScreenshot();
                if (form.ShowDialog() != DialogResult.OK) return;
                if (form.Screenshot != null)
                {
                    MainFormSingleton.ActivePictureBox.BackgroundImage = form.Screenshot;
                }
            };

            /// <summary>
            /// 
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            luminanceProfileToolStripMenuItem.Click += delegate(object sender, EventArgs e)
            {
                Debug.WriteLine(string.Format("{0}:{1}", luminanceProfileToolStripMenuItem.Name, "luminance profile"));
                UnsafeBitmap bitmap = MainFormSingleton.ActivePictureBox.BackgroundImage;
                ShowProfile(bitmap, "Luminance Profile", true, PROCESSING_MODE.Luminance);
            };


            GuiHelper.SetEventHandler(ausschlussToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Ausschluss().Execute)));
            GuiHelper.SetEventHandler(farbigAbwedelnToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new FarbigAbwedeln().Execute)));
            GuiHelper.SetEventHandler(farbigNachbelichtenToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new FarbigNachbelichten().Execute)));
            GuiHelper.SetEventHandler(hartesLichtToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new HartesLicht().Execute)));
            GuiHelper.SetEventHandler(lichtpunkteToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Lichtpunkte().Execute)));
            GuiHelper.SetEventHandler(weichesLichtToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new WeichesLicht().Execute)));
            GuiHelper.SetEventHandler(linearesLichtToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new LinearesLicht().Execute)));
            GuiHelper.SetEventHandler(strahlendesLichtToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new StrahlendesLicht().Execute)));
            GuiHelper.SetEventHandler(überlagernToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Ueberlagern().Execute)));
            GuiHelper.SetEventHandler(multiplizierenToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Multiplizieren().Execute)));
            GuiHelper.SetEventHandler(umgekehrtMultiplizierenToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new UmgekehrtMultiplizieren().Execute)));
            GuiHelper.SetEventHandler(linearAbwedelnToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new LinearAbwedeln().Execute)));
            GuiHelper.SetEventHandler(linearNachbelichtenToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new LinearNachbelichten().Execute)));

            //Geometric Transformations
            GuiHelper.SetEventHandler(imageTransformationToolStripMenuItem, new ActionImageTransformation());
            //Binarization
            GuiHelper.SetEventHandler(barcodeToolStripMenuItem, new ActionBarcode());
            GuiHelper.SetEventHandler(adaptiverThresholdMedianToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new AdaptiveThresholding(THRESHOLDING_MODE.MEDIAN).Execute)));
            GuiHelper.SetEventHandler(thresholdMeanToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new AdaptiveThresholding(THRESHOLDING_MODE.MEAN).Execute)));
            GuiHelper.SetEventHandler(thresholdMinMaxToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new AdaptiveThresholding(THRESHOLDING_MODE.MIN_MAX).Execute)));
            GuiHelper.SetEventHandler(threshold2ToolStripMenuItem, new ActionThreshold(new Threshold2()));
            GuiHelper.SetEventHandler(threshold3ToolStripMenuItem, new ActionThreshold(new Threshold3()));
            GuiHelper.SetEventHandler(threshold4ToolStripMenuItem, new ActionThreshold(new Threshold4()));
            GuiHelper.SetEventHandler(thresholdToolStripMenuItem, new ActionThreshold());
            GuiHelper.SetEventHandler(singleLayerMultiThresholdToolStripMenuItem, new ActionSingleLayerMultipleThreshold());
            GuiHelper.SetEventHandler(sISThresholdToolStripMenuItem, new ActionThreshold(new SISThreshold()));
            GuiHelper.SetEventHandler(variationalThresholdToolStripMenuItem, new ActionThreshold(new VariationThreshold()));
            GuiHelper.SetEventHandler(environmentThresholdToolStripMenuItem, new ActionThreshold(new EnvironmentThreshold()));
            GuiHelper.SetEventHandler(hysteresisThresholdToolStripMenuItem, new ActionThreshold(new HysteresisThreshold()));
            GuiHelper.SetEventHandler(multiThresholdToolStripMenuItem, new ActionForm(new FormMultiThreshold()));

            //Edges
            BaseImageFilter edgeDetectHomogenity = new EdgeDetectHomogenity();
            GuiHelper.SetEventHandler(homogenToolStripMenuItem, new ActionEdgeFilter(edgeDetectHomogenity));
            GuiHelper.SetEventHandler(laplaceToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new EmbossLaplacian().Execute)));
            GuiHelper.SetEventHandler(cannyToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new CannyEdgeDetector().Execute)));

            BaseImageFilter edgeDetectConvolution = new EdgeDetectConvolution((short)EdgeDetectMode.EDGE_DETECT_KIRSH, 0);
            GuiHelper.SetEventHandler(kirshToolStripMenuItem, new ActionEdgeFilter(edgeDetectConvolution));

            edgeDetectConvolution = new EdgeDetectConvolution((short)EdgeDetectMode.EDGE_DETECT_PREWITT, 0);
            GuiHelper.SetEventHandler(prewittToolStripMenuItem, new ActionEdgeFilter(edgeDetectConvolution));
            GuiHelper.SetEventHandler(schnellToolStripMenuItem, new ActionEdgeFilter(new EdgeDetectQuick()));
            GuiHelper.SetEventHandler(sobelToolStripMenuItem, new ActionEdge((short)EdgeDetectMode.EDGE_DETECT_SOBEL));
            GuiHelper.SetEventHandler(konvolutionToolStripMenuItem, new ActionConvolution());
            GuiHelper.SetEventHandler(anpassbareKonvolutionToolStripMenuItem, new ActionConvolution());
            GuiHelper.SetEventHandler(lambdaKonvolutionToolStripMenuItem, new ActionConvolution());

            GuiHelper.SetEventHandler(horizontalToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new EdgeDetectHorizontal().Execute)));
            GuiHelper.SetEventHandler(verticalToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new EdgeDetectVertical().Execute)));
            GuiHelper.SetEventHandler(differenzToolStripMenuItem, new ActionEdgeFilter(new EdgeDetectDifference()));
            GuiHelper.SetEventHandler(emphasizeToolStripMenuItem, new ActionParameterByte(typeof(EdgeEnhance)));
            GuiHelper.SetEventHandler(kantenFindenToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new FindContours().Execute)));
            GuiHelper.SetEventHandler(gaussianOfLaplacianKantenToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new GaussianOfLaplacianEdge().Execute)));
            GuiHelper.SetEventHandler(moravecToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Moravec().Execute)));
            GuiHelper.SetEventHandler(kompassToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Compass().Execute)));
            GuiHelper.SetEventHandler(colorDifferenceToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new ColorDifferenceUnsafe().Execute))); //ColorDiff
            GuiHelper.SetEventHandler(distanzToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new DistanceFilter(DISTANCE_MODE.CUSTOM).Execute))); //ColorDiff

            //Corners
            GuiHelper.SetEventHandler(eckeToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Corner().Execute)));
            GuiHelper.SetEventHandler(ecke2ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Corner2().Execute)));
            GuiHelper.SetEventHandler(zeroCrossingEdgeToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new ZeroCrossingEdge().Execute)));
            GuiHelper.SetEventHandler(harrisPlesseyToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new HarrisPlessey().Execute)));
            GuiHelper.SetEventHandler(susanToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Susan().Execute)));
            GuiHelper.SetEventHandler(wangBradyToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new WangBrady().Execute)));
            GuiHelper.SetEventHandler(trajkovicToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Trajkovic().Execute)));

            //Colors
            GuiHelper.SetEventHandler(grauToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new GrayScale().Execute)));
            GuiHelper.SetEventHandler(segmentationToolStripMenuItem, new ActionSegmentate());

            GuiHelper.SetEventHandler(basisFarbSegmentierungToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new BaseColorSegmentation().Execute)));
            GuiHelper.SetEventHandler(basisFarbSegmentierung2ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new BaseColorSegmentation2().Execute)));
            GuiHelper.SetEventHandler(basisFarbSegmentierung3ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new BaseColorSegmentation(BASECOLOR_SEGMENTATION_MODE.DEFAULT2).Execute)));
            GuiHelper.SetEventHandler(basisFarbSegmentierung4ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new BaseColorSegmentation(BASECOLOR_SEGMENTATION_MODE.BASECOLOR).Execute)));

            GuiHelper.SetEventHandler(ownMeanShiftToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new MeanShift().Execute)));
            GuiHelper.SetEventHandler(sepiaToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Sepia().Execute)));
            GuiHelper.SetEventHandler(störungenEntfernenToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new NoiseRemoval().Execute)));
            GuiHelper.SetEventHandler(contrastStretchErweiterungToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new ContrastStretch().Execute)));
            GuiHelper.SetEventHandler(invertierToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Invert().Execute)));
            GuiHelper.SetEventHandler(gammaToolStripMenuItem1, new ActionGamma());
            GuiHelper.SetEventHandler(contrastToolStripMenuItem1, new ActionBrightnessContrast());
            GuiHelper.SetEventHandler(colorFilterToolStripMenuItem, new ActionColorFilter());

            GuiHelper.SetEventHandler(brightnessToolStripMenuItem, new ActionBrightnessContrast());
            GuiHelper.SetEventHandler(saturationToolStripMenuItem, new ActionHueSaturationLightness());

            GuiHelper.SetEventHandler(rGBCMYExtractionToolStripMenuItem, new ActionRGBCMYExtract());
            GuiHelper.SetEventHandler(colorDifference2ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new ColorDifference2().Execute)));
            //SetEventHandler(farbauswahlToolStripMenuItem, new ActionChooseColor(pictureBox1));
            GuiHelper.SetEventHandler(rotateChannelsToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new RotateChannels().Execute)));
            GuiHelper.SetEventHandler(multiplesOfWhiteToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new FilterMultiples().Execute)));
            GuiHelper.SetEventHandler(medianToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Median().Execute)));
            GuiHelper.SetEventHandler(ditherToolStripMenuItem, new ActionDither());
            GuiHelper.SetEventHandler(sortChannelsAscendingToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new SortChannels(true).Execute)));
            GuiHelper.SetEventHandler(sortChannelsDescendingToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new SortChannels(false).Execute)));
            GuiHelper.SetEventHandler(watershedSegmentationToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new WatershedGrayscale().Execute)));
            GuiHelper.SetEventHandler(colorBalanceToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new ColorBalance().Execute)));
            GuiHelper.SetEventHandler(toolStripHueSaturationLightness, new ActionForm(new FormHueSaturationLightness()));
            GuiHelper.SetEventHandler(channelMixerToolStripMenuItem, new ActionForm(new FormChannelMixer()));
            GuiHelper.SetEventHandler(channelsMinMaxToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new ChannelMinMax().Execute)));
            GuiHelper.SetEventHandler(whitePointToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new WhiteColorBalance(WHITECOLORBALANCE_MODE.FIND_NEARLY_WHITE_SPOTS).Execute)));
            GuiHelper.SetEventHandler(normalizeToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Normalize(Normalization_Mode.RGBUseRange).Execute)));

            GuiHelper.SetEventHandler(variationsToolStripMenuItem, new ActionForm(new FormVariations()));
            GuiHelper.SetEventHandler(adjustBrightnessToolStripMenuItem1, new ActionAdjustBrightness());
            GuiHelper.SetEventHandler(channelMathToolStripMenuItem, new ActionForm(new FormChannelMath()));
            GuiHelper.SetEventHandler(variableThresholdToolStripMenuItem, new ActionVariableThreshold());

            //Miscellaneous
            GuiHelper.SetEventHandler(noiseToolStripMenuItem, new ActionNoise());
            GuiHelper.SetEventHandler(lonelyPixelsToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new LonelyPixel().Execute)));
            GuiHelper.SetEventHandler(lonelyHolesToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new LonelyHoles().Execute)));
            GuiHelper.SetEventHandler(differenz2ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Difference2().Execute)));

            GuiHelper.SetEventHandler(unsharpMaskToolStripMenuItem, new ActionUnsharpMask());
            GuiHelper.SetEventHandler(gaussianUnsharpToolStripMenuItem, new ActionParameter(typeof(GaussianBlur)));

            //SetEventHandler(horizontalToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(RotateFlipType.RotateNoneFlipX)));
            //  SetEventHandler(vertikalToolStripMenuItem, new ActionExecuteDelegate());
            //                        SetEventHandler(punktToolStripMenuItem, new ActionExecuteDelegate());

            //Mirroring
            GuiHelper.SetEventHandler(horizontalToolStripMenuItem1, new ActionRotateOrMirroring(RotateFlipType.RotateNoneFlipX));
            GuiHelper.SetEventHandler(verticalToolStripMenuItem1, new ActionRotateOrMirroring(RotateFlipType.RotateNoneFlipX));

            //Rotate
            GuiHelper.SetEventHandler(degree90ToolStripMenuItem, new ActionRotateOrMirroring(RotateFlipType.Rotate90FlipNone));
            GuiHelper.SetEventHandler(degree180ToolStripMenuItem1, new ActionRotateOrMirroring(RotateFlipType.Rotate180FlipNone));
            GuiHelper.SetEventHandler(degree270ToolStripMenuItem2, new ActionRotateOrMirroring(RotateFlipType.Rotate270FlipNone));

            GuiHelper.SetEventHandler(cWToolStripMenuItem, new ActionRotateOrMirroring(RotateFlipType.Rotate90FlipNone));
            GuiHelper.SetEventHandler(cWToolStripMenuItem1, new ActionRotateOrMirroring(RotateFlipType.Rotate90FlipNone));
            GuiHelper.SetEventHandler(cCWToolStripMenuItem, new ActionRotateOrMirroring(RotateFlipType.Rotate90FlipNone));
            GuiHelper.SetEventHandler(cCWToolStripMenuItem1, new ActionRotateOrMirroring(RotateFlipType.Rotate90FlipNone));
            GuiHelper.SetEventHandler(arbitraryToolStripMenuItem, new ActionForm(new FormSizeRotation()));

            //experimental
            GuiHelper.SetEventHandler(binaryDilationToolStripMenuItem, new ActionDilation(typeof(BinaryDilation)));
            GuiHelper.SetEventHandler(grauDilationToolStripMenuItem, new ActionDilation(typeof(GrayDilation)));
            GuiHelper.SetEventHandler(rundenToolStripMenuItem2, new ActionThreshold(new RoundColors()));
            GuiHelper.SetEventHandler(round5ToolStripMenuItem1, new ActionRoundColor(5));
            GuiHelper.SetEventHandler(round10ToolStripMenuItem1, new ActionRoundColor(10));
            GuiHelper.SetEventHandler(round20ToolStripMenuItem1, new ActionRoundColor(20));
            GuiHelper.SetEventHandler(round50ToolStripMenuItem1, new ActionRoundColor(50));
            GuiHelper.SetEventHandler(round100ToolStripMenuItem1, new ActionRoundColor(100));
            GuiHelper.SetEventHandler(round150ToolStripMenuItem, new ActionRoundColor(150));
            GuiHelper.SetEventHandler(round200ToolStripMenuItem, new ActionRoundColor(200));

            //Unknown
            //GuiHelper.SetEventHandler(toolStripMenuItemUnknown1, new ActionSetBitmap(new UnsafeBitmapDelegate(ImageFilters.FastFourierTransformation)));
            //GuiHelper.SetEventHandler(toolStripMenuItemUnknown2, new ActionSetBitmap(new UnsafeBitmapDelegate(ImageFilters.menuItem13_Click)));
            //GuiHelper.SetEventHandler(toolStripMenuItemUnknown3, new ActionSetBitmap(new UnsafeBitmapDelegate(ImageFilters.menuItem14_Click)));
            //GuiHelper.SetEventHandler(toolStripMenuItemUnknown4, new ActionSetBitmap(new UnsafeBitmapDelegate(ImageFilters.menuItem15_Click)));
            //GuiHelper.SetEventHandler(toolStripMenuItemUnknown5, new ActionSetBitmap(new UnsafeBitmapDelegate(ImageFilters.menuItem16_Click)));
            //GuiHelper.SetEventHandler(toolStripMenuItemUnknown6, new ActionSetBitmap(new UnsafeBitmapDelegate(ImageFilters.menuItem30_Click)));
            //GuiHelper.SetEventHandler(toolStripMenuItemUnknown7, new ActionSetBitmap(new UnsafeBitmapDelegate(ImageFilters.menuItem31_Click)));
            //GuiHelper.SetEventHandler(toolStripMenuItemUnknown8, new ActionSetBitmap(new UnsafeBitmapDelegate(ImageFilters.Walsh)));
            //GuiHelper.SetEventHandler(toolStripMenuItemUnknown9, new ActionSetBitmap(new UnsafeBitmapDelegate(ImageFilters.menuItem34_Click)));
            //GuiHelper.SetEventHandler(toolStripMenuItemUnknown10, new ActionSetBitmap(new UnsafeBitmapDelegate(ImageFilters.menuItem36_Click)));

            GuiHelper.SetEventHandler(weightingToolStripMenuItem, new ActionWeighting());
            GuiHelper.SetEventHandler(backgroundEstimationToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new EstimateBoundingBox().Execute)));
            GuiHelper.SetEventHandler(backgroundEstimationByEdgesStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new EstimateBoundingBoxByUsingEdges().Execute)));
            //GuiHelper.SetEventHandler(linesExperimentalToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new LinesExperimental().Execute)));
            GuiHelper.SetEventHandler(ahsbColorToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new AhsbColor().Execute)));
            GuiHelper.SetEventHandler(dilationToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Dilation().Execute)));
            GuiHelper.SetEventHandler(experimental1ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Experimental1().Execute)));
            GuiHelper.SetEventHandler(experimental2ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Experimental2().Execute)));
            GuiHelper.SetEventHandler(experimental3ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Experimental3().Execute)));
            GuiHelper.SetEventHandler(experimental4ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Experimental4().Execute)));
            GuiHelper.SetEventHandler(experimental5ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Experimental5().Execute)));

            //Experimental Morphology
            GuiHelper.SetEventHandler(experimentalThickeningToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new ExperimentalThickening().Execute)));
            GuiHelper.SetEventHandler(experimentalThinningToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new ExperimentalThinning().Execute)));
            GuiHelper.SetEventHandler(experimentalSkeletonizeToolStripMenuItem1, new ActionExecuteDelegate(new VoidDelegate(new ExperimentalSkeletonize().Execute)));

            //Frequency
            GuiHelper.SetEventHandler(lowpassToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Lowpass().Execute)));
            GuiHelper.SetEventHandler(highpassToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Highpass().Execute)));
            GuiHelper.SetEventHandler(bandpassToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Bandpass().Execute)));
            GuiHelper.SetEventHandler(gabor1ToolStripMenuItem, new ActionForm(new FormGabor()));
            GuiHelper.SetEventHandler(gabor2ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Gabor2().Execute)));
            GuiHelper.SetEventHandler(crossingToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Crossing().Execute)));

            GuiHelper.SetEventHandler(segmentation2ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new SimpleSegmentation().Execute)));
            GuiHelper.SetEventHandler(fastSegmentationToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new FastSegmentation().Execute)));

            //Morphology
            GuiHelper.SetEventHandler(openToolStripMenuItem1, new ActionExecuteDelegate(new VoidDelegate(new Open().Execute)));
            GuiHelper.SetEventHandler(closeToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Close().Execute)));
            GuiHelper.SetEventHandler(erosionToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Erode().Execute)));
            GuiHelper.SetEventHandler(dilatationToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Dilate().Execute)));
            GuiHelper.SetEventHandler(skeletonizeToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Skeletonize().Execute)));
            GuiHelper.SetEventHandler(topHatToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new TopHat().Execute)));
            GuiHelper.SetEventHandler(bottomHatToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new BottomHat().Execute)));
            GuiHelper.SetEventHandler(thinningToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Thinning().Execute)));
            GuiHelper.SetEventHandler(thickeningToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Thickening().Execute)));
            GuiHelper.SetEventHandler(hitAndMissToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new HitAndMiss().Execute)));

            GuiHelper.SetEventHandler(fischaugeToolStripMenuItem, new ActionFishEye());
            GuiHelper.SetEventHandler(schärfenToolStripMenuItem, new ActionParameter(typeof(Sharpen)));

            //multiple Sources
            GuiHelper.SetEventHandler(oRToolStripMenuItem, new ActionTwoSources());
            GuiHelper.SetEventHandler(aNDToolStripMenuItem, new ActionTwoSources());
            GuiHelper.SetEventHandler(nORToolStripMenuItem, new ActionTwoSources());
            GuiHelper.SetEventHandler(nANDToolStripMenuItem, new ActionTwoSources());
            GuiHelper.SetEventHandler(subtractionToolStripMenuItem, new ActionTwoSources());
            GuiHelper.SetEventHandler(additionToolStripMenuItem, new ActionTwoSources());

            //more below
            GuiHelper.SetEventHandler(rangFilterToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Ranking().Execute)));
            GuiHelper.SetEventHandler(verpixelnToolStripMenuItem, new ActionParameter(typeof(Coarse), true));
            GuiHelper.SetEventHandler(gefüllteKreiseToolStripMenuItem, new ActionParameter(typeof(Coarse), false));
            GuiHelper.SetEventHandler(sigmaToolStripMenuItem, new ActionParameter(typeof(Sigma)));

            //Luminance
            GuiHelper.SetEventHandler(eigeneLuminanzToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new MyLuminance().Execute)));

            //Lines
            GuiHelper.SetEventHandler(vertikaleLinienToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new VerticalLines().Execute)));
            GuiHelper.SetEventHandler(horizontaleLinienToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new HorizontalLines().Execute)));
            GuiHelper.SetEventHandler(gradLinienToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Lines45Degrees().Execute)));
            GuiHelper.SetEventHandler(lineDetectorToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new LineDetector().Execute)));

            //Skin
            GuiHelper.SetEventHandler(hautfilter1ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new GaussianSkin().Execute)));
            GuiHelper.SetEventHandler(hautfilter1ToolStripMenuItem1, new ActionExecuteDelegate(new VoidDelegate(new SkinFilter1().Execute)));
            GuiHelper.SetEventHandler(hautfilter2ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new SkinFilter2().Execute)));
            GuiHelper.SetEventHandler(hautfilter3ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new SkinFilter3().Execute)));
            GuiHelper.SetEventHandler(hautfilter4ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new SkinFilter4().Execute)));
            GuiHelper.SetEventHandler(hautfilter5ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new SkinFilter5().Execute)));
            GuiHelper.SetEventHandler(hautfilter6ToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new SkinFilter6().Execute)));
            InitFileDialog();

            //Correcture
            GuiHelper.SetEventHandler(deinterlaceToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Deinterlace().Execute)));
            GuiHelper.SetEventHandler(konservativGlättenToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new ConservativeSmoothing().Execute)));
            GuiHelper.SetEventHandler(dejitterToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Dejitter().Execute)));
            GuiHelper.SetEventHandler(meanToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new MeanRemoval().Execute)));
            GuiHelper.SetEventHandler(medianToolStripMenuItem1, new ActionExecuteDelegate(new VoidDelegate(new Median().Execute)));
            GuiHelper.SetEventHandler(crimminsToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new CrimminsSpeckleRemoval().Execute)));
            GuiHelper.SetEventHandler(farbenVerbessernToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Normalize(Normalization_Mode.YUV).Execute)));
            GuiHelper.SetEventHandler(antivignettingToolStripMenuItem, new ActionForm(new FormAntivignetting()));
            GuiHelper.SetEventHandler(enhanceGrayContrastToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new EnhanceGrayContrast().Execute)));
            GuiHelper.SetEventHandler(flattenToolStripMenuItem, new ActionForm(new FormFlatten()));
            GuiHelper.SetEventHandler(improveMultiplyToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Improve(new ImproveMode()).Execute)));
            GuiHelper.SetEventHandler(improveNegMultiplyToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Improve(new ImproveModeNegativeMultiply()).Execute)));


            //Displacement
            GuiHelper.SetEventHandler(jitterToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new Jitter().Execute)));

            //Macro
            GuiHelper.SetEventHandler(similarCannyEdgeToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new CannySimilar().Execute)));
            GuiHelper.SetEventHandler(complexSkinDetectionToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new ComplexSkinDetection().Execute)));
            GuiHelper.SetEventHandler(contourExtraction2StepsToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new ContourExtractionTwoSteps().Execute)));
            GuiHelper.SetEventHandler(lowpassHighpassEdgesToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new LowpassHighpassEdges().Execute)));

            MacroFilter macroFilter2xRGB2 = new MacroFilter();
            macroFilter2xRGB2.FilterList.AddRange(new IteratedFilter[] { new RGBFilter2(), new RGBFilter2() });
            GuiHelper.SetEventHandler(rGBFilter22xToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(macroFilter2xRGB2.Execute)));
            GuiHelper.SetEventHandler(correctionToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new FoggyPictureCorrection().Execute)));

            MacroFilter macroFilterImprove = new MacroFilter();
            macroFilterImprove.FilterList.AddRange(new IteratedFilter[] { new UmgekehrtMultiplizieren(), new Invert(), new UmgekehrtMultiplizieren(), new Invert() });
            GuiHelper.SetEventHandler(improveToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(macroFilterImprove.Execute)));

            GuiHelper.SetEventHandler(gaussianUnsharpSubToolStripMenuItem,
                new ActionExecuteDelegate(
                    new VoidDelegate(delegate(UnsafeBitmap _bitmap)
                        {
                            GaussianBlur gaussianBlur = new GaussianBlur(10);
                            UnsafeBitmap bitmapBlurred = gaussianBlur.ExecuteCloned(_bitmap);
                            int nIterations = 3;
                            for (int i = 0; i < nIterations; i++)
                            {
                                gaussianBlur.Execute(bitmapBlurred);
                            }
                            UnsafeBitmap bitmapSource = _bitmap;
                            UnsafeBitmap imageSource = bitmapBlurred;
                            UnsafeBitmap bitmap = new Sub().Process(bitmapSource, imageSource);
                            imageSource.Dispose();
                            bitmapSource.Dispose();
                            MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap.InternalBitmap;
                            return bitmap;
                        })));

            //GuiHelper.SetEventHandler(convertToGrayscaleRangeFilterToolStripMenuItem, new ActionExecuteDelegate(new VoidDelegate(new GrayScaleRangeFilter().Execute)));

            GuiHelper.SetEventHandler(templateMatchingToolStripMenuItem, new ActionTemplateMatching());
            //Histogram

            //Extractors
            GuiHelper.SetEventHandler(colorBlobExtractorToolStripMenuItem, new ActionColorBlobExtractor());
            GuiHelper.SetEventHandler(simpleBlobExtractorToolStripMenuItem, new ActionSimpleBlobExtractor());
            GuiHelper.SetEventHandler(autoCropToolStripMenuItem, new ActionAutoCrop(true));
            GuiHelper.SetEventHandler(autoCropToolStripMenuItem1, new ActionAutoCrop(false));
            GuiHelper.SetEventHandler(autoCropAnalyseModeToolStripMenuItem, new ActionAutoCrop(false, AUTOCROP_MODE.COLORDEPENDENCYLINES));
            GuiHelper.SetEventHandler(cropToolStripMenuItem, new ActionForm(new FormCrop()));
            GuiHelper.SetEventHandler(objektExtraktorToolStripMenuItem, new ActionObjectExtractor());
            GuiHelper.SetEventHandler(impainterToolStripMenuItem, new ActionImpainter());
            GuiHelper.SetEventHandler(cutFromMaskToolStripMenuItem, new ActionCutFromMask());
            GuiHelper.SetEventHandler(extractChannelsToolStripMenuItem, new ActionExtractChannels());
        }

        private static void Histogram()
        {
            //Debug.WriteLine();
            UnsafeBitmap _bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
            Histogram histogram = new Histogram(_bitmap);
            _bitmap.UnlockImage();
            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        private void HueProfile()
        {
            Debug.WriteLine(string.Format("{0}: {1}", hueKreuzToolStripMenuItem.Name, hueProfilToolStripMenuItem));
            UnsafeBitmap _bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
            ShowProfile(_bitmap, "Hue-Profil", false, PROCESSING_MODE.Hue);
        }

        /// <summary>
        /// Open From Url
        /// </summary>
        private void OpenFromUrl()
        {
            FormTypeCommand formTypeCommand = new FormTypeCommand();
            if (formTypeCommand.ShowDialog() != DialogResult.OK) return;
            Image image = Helper.DownloadImageFromUrl(formTypeCommand.InputText);
            int nCount = Helper.GetFormCount();
            if (nCount == 0)
            {
                GuiHelper.CreateNewChild();
            }
            MainFormSingleton.ActivePictureBox.BackgroundImage = image;
        }

        /// <summary>
        /// Open Video
        /// </summary>
        private void OpenVideo()
        {
            System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog();
            if (fd.ShowDialog() != DialogResult.OK) return;
            try
            {
                m_AVI.Open(fd.FileName);
                FormFrameAccess formFrameAccess = new FormFrameAccess();
                formFrameAccess.Show(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Open New Picture
        /// </summary>
        private void OpenNewPicture()
        {
            Debug.WriteLine("open");
            int nCount = 0;
            nCount = Helper.GetFormCount();
            if (nCount == 0)
            {
                GuiHelper.CreateNewChild();
            }

            LoadPicture(null);
        }

        /// <summary>
        /// Reload
        /// </summary>
        private void Reload()
        {
            string sFileName = MainFormSingleton.ActiveFormChild.LoadedPictureFullQualifiedPath;
            Debug.WriteLine(string.Format("Reload: {0}", sFileName));
            if (!string.IsNullOrEmpty(sFileName))
            {
                LoadPicture(sFileName);
            }
        }

        /// <summary>
        /// Show testcontrols
        /// </summary>
        /// <param name="bComputerNameIsTest"></param>
        protected void ShowTestControls(bool bComputerNameIsTest)
        {
            this.cbTest.Visible = bComputerNameIsTest;
            this.cbTest2.Visible = bComputerNameIsTest;
            this.cbTest3.Visible = bComputerNameIsTest;
            this.cbTest4.Visible = bComputerNameIsTest;
            this.cbTest5.Visible = bComputerNameIsTest;
            this.cbTest6.Visible = bComputerNameIsTest;
        }

        /// <summary>
        /// Init a special file dialog if needed.
        /// </summary>
        protected void InitFileDialog()
        {
            panel = new Panel();
            panel.BorderStyle = BorderStyle.Fixed3D;

            // Add a picture box to the "preview" panel
            m_PictureBox = new PictureBox();
            panel.Controls.Add(m_PictureBox);
            m_PictureBox.Dock = DockStyle.Fill;
            m_PictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
            m_PictureBox.Click += new EventHandler(picBox_Click);
            m_PictureBox.BackgroundImageLayout = ImageLayout.Zoom;
            // Create and show the OpenFile Dialog
        }

        /// <summary>
        /// Handles the Click event of the picBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void picBox_Click(object sender, EventArgs e)
        {
            Bitmap bitmap = m_PictureBox.BackgroundImage as Bitmap;
            if (bitmap != null)
            {
                string sMessage = String.Format("Image width: {0} pixels\nImage height: {1} pixels", bitmap.Width, bitmap.Height);
                MessageBox.Show(sMessage, "Extensible Dialogs Test");
            }
        }

        /// <summary>
        /// Handles the Click event of the cbMisc control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void cbMisc_Click(object sender, EventArgs e)
        {
            Debug.WriteLine(string.Format("{0}:{1}", miscToolStripMenuItem.Name, "misc"));

            //FastConvolution();
            //SkinFilter();
            //Unknown();

            Bitmap _bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
            new FindContours().ExecuteChannelled(_bitmap, true, true, true, true);
            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        /// <summary>
        /// Tests the action thread proc.
        /// </summary>
        protected void testActionThreadProc()
        {
            new ActionTest(MainFormSingleton.ActivePictureBox).Run(this, EventArgs.Empty);
        }

        /// <summary>
        /// Handles the Click event of the cbTest control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void cbTest_Click(object sender, EventArgs e)
        {
            Helper.Test();
        }

        /// <summary>
        /// Load a picture
        /// </summary>
        /// <param name="_sFileName"></param>
        /// <returns></returns>
        public string LoadPicture(string _sFileName)
        {
            Debug.WriteLine(string.Format("Loadpicture {0}", _sFileName));
            MainFormSingleton.ActiveFormChild.LoadedPictureFullQualifiedPath = _sFileName;
            SelectablePictureBox pictureBox1 = MainFormSingleton.ActivePictureBox;
            if (pictureBox1 == null)
            {
                return null;
            }

            if (string.IsNullOrEmpty(_sFileName))
            {
                IFileDialog fd = OpenDecodableFileDialog();

                if (fd.ShowDialog() == DialogResult.OK)
                {
                    MainFormSingleton.ActiveFormChild.LoadedPictureFullQualifiedPath = fd.FileName;
                }
                else
                {
                    return null;
                }
            }

            if (!string.IsNullOrEmpty(MainFormSingleton.ActiveFormChild.LoadedPictureFullQualifiedPath))
            {
                try
                {
                    UnsafeBitmap bitmap = UnsafeBitmap.FromFile(MainFormSingleton.ActiveFormChild.LoadedPictureFullQualifiedPath);
                    bitmap.Dispose();

                    Image imageFromFile = bitmap.InternalBitmap;
                    if (BitmapFunctions.IsIndexed((Bitmap)imageFromFile))
                    {
                        imageFromFile = BitmapFunctions.GetNonIndexedBitmap((Bitmap)imageFromFile);
                    }
                    MainFormSingleton.ActivePictureBox.BackgroundImage = imageFromFile;
                    m_aColorRect.Clear();
                    MainFormSingleton.ActivePictureBox.BackgroundImageLayout = ImageLayout.Zoom;
                    return _sFileName;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    if (automaticToolStripMenuItem.Checked)
                    {
                        Image image = OpenCoded(MainFormSingleton.ActiveFormChild.LoadedPictureFullQualifiedPath);
                        MainFormSingleton.ActivePictureBox.BackgroundImage = image;
                        MainFormSingleton.ActivePictureBox.BackgroundImageLayout = ImageLayout.Zoom;
                        return _sFileName;
                    }
                    else
                    {
                        MessageBox.Show(String.Format("{0} or wrong file format", ex.Message));
                    }
                }
            }
            return _sFileName;
        }

        /// <summary>
        /// Shows the profile.
        /// </summary>
        /// <param name="bitmap">The bitmap.</param>
        protected void ShowProfile(UnsafeBitmap bitmap)
        {
            ShowProfile(bitmap, string.Empty, false, PROCESSING_MODE.Color);
        }

        /// <summary>
        /// Shows the profile.
        /// </summary>
        /// <param name="bitmap">The bitmap.</param>
        /// <param name="_sTitle">The _s title.</param>
        protected void ShowProfile(UnsafeBitmap bitmap, string _sTitle)
        {
            ShowProfile(bitmap, _sTitle, false, PROCESSING_MODE.Color);
        }

        /// <summary>
        /// Shows the profile.
        /// </summary>
        /// <param name="bitmap">The bitmap.</param>
        /// <param name="_sTitle">The _s title.</param>
        /// <param name="_bModal">if set to <c>true</c> [_b modal].</param>
        /// <param name="_processing_mode">The _processing_mode.</param>
        /// <returns></returns>
        protected Form ShowProfile(UnsafeBitmap bitmap, string _sTitle, bool _bModal, PROCESSING_MODE _processing_mode)
        {
            FormProfile formProfile = new FormProfile(bitmap, _processing_mode);
            formProfile.Text = _sTitle;
            formProfile.FormBorderStyle = FormBorderStyle.SizableToolWindow;
            formProfile.GetPicture += new EventHandler(formProfile_GetPicture);
            formProfile.StartPosition = FormStartPosition.CenterScreen;
            if (_bModal)
            {
                formProfile.ShowDialog(this);
            }
            else
            {
                formProfile.Show(this);
            }
            return formProfile;
        }

        /// <summary>
        /// Handles the GetPicture event of the formProfile control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void formProfile_GetPicture(object sender, EventArgs e)
        {
            Profile(sender);
        }

        private static void Profile(object sender)
        {
            FormProfile formProfile = (FormProfile)sender;
            MainFormSingleton.ActivePictureBox.BackgroundImage = formProfile.Bitmap;
        }

        /// <summary>
        /// Handles the Click event of the zuschneidenToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void zuschneidenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_bCutImage = true;
        }

        /// <summary>
        /// Event handler that is called when the user clicks on a file or folder inside the dialog
        /// </summary>
        /// <param name="path">the full path of the currently-selected file</param>
        public void ofd_SelectionChanged(object sender, SelectionEventArgs e)
        {
            SelectionChanged(e);
        }

        private void SelectionChanged(SelectionEventArgs e)
        {
            string _sPath = e.FileName;
            // Check the path points to something valid before trying to display the contents
            if (!File.Exists(_sPath)) return;
            if (!Path.HasExtension(_sPath)) return;
            string ext = Path.GetExtension(_sPath).ToLower();
            if (ext == ".jpg" || ext == ".gif" || ext == ".png")
            {
                try
                {
                    m_PictureBox.BackgroundImage = new Bitmap(_sPath);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    if (automaticToolStripMenuItem.Checked)
                    {
                        Image image = OpenCoded(_sPath);
                        m_PictureBox.BackgroundImage = image;
                    }
                }
            }
        }

        /// <summary>
        /// Opens the coded.
        /// </summary>
        /// <param name="_sFileName">Name of the _s file.</param>
        /// <returns></returns>
        protected Image OpenCoded(string _sFileName)
        {
            Debug.WriteLine(string.Format("Open coded: {0}", _sFileName));
            try
            {
                BinaryCoder coder = new BinaryCoder();
                Image image = coder.GetAsImage(_sFileName);

                m_aColorRect.Clear();
                MainFormSingleton.ActivePictureBox.BackgroundImage = image;
                return image;
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("{0} oder wrong file format", ex.Message));
                return null;
            }
        }

        /// <summary>
        /// Handles the Click event of the openCodedToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void openCodedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenCoded();
        }

        private void OpenCoded()
        {
            IFileDialog fd = OpenDecodableFileDialog();
            if (fd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            OpenCoded(fd.FileName);
        }

        /// <summary>
        /// opens a decodable file dialog
        /// </summary>
        /// <returns></returns>
        private IFileDialog OpenDecodableFileDialog()
        {
            return Helper.OpenDecodableFileDialog(m_bUseStandardFileDialog);
        }

        /// <summary>
        /// Handles the Click event of the batchcoderToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void batchcoderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BatchCoder();
        }

        private void BatchCoder()
        {
            Thread thread = new Thread(new ThreadStart(BatchCode));
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }

        /// <summary>
        /// Batches the code.
        /// </summary>
        public void BatchCode()
        {
            BinaryCoder coder = new BinaryCoder();
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() != DialogResult.OK) return;
            string[] aFile = Directory.GetFiles(folderBrowserDialog.SelectedPath, "*.*", SearchOption.AllDirectories);

            Form form = new Form();

            this.Invoke(new MethodInvoker(delegate() { form.Show(this); }));
            ListBox listBox = new ListBox();
            this.Invoke(new MethodInvoker(delegate()
            {
                listBox.Parent = form;
                listBox.Dock = DockStyle.Fill;
            }));

            int nCount = -1;
            foreach (string sFile in aFile)
            {
                nCount++;
                if (sFile.EndsWith("_coded"))
                {
                    this.Invoke(
                        new MethodInvoker(
                            delegate()
                            {
                                listBox.Items.Add(string.Format("{1}.)\t {0} skipped. ............ Is already coded!", sFile, nCount));
                            }
                        )
                    );
                    continue;
                }
                bool bSuccess = coder.Code(sFile);
                this.Invoke(
                    new MethodInvoker(
                        delegate()
                        {
                            listBox.Items.Add(string.Format("{2}.)\t Codierung of {0} was ............ {1}", sFile, bSuccess ? "successful" : "errorneous", nCount));
                            listBox.SelectedIndex = listBox.Items.Count - 1;
                            listBox.Update();
                        }
                    )
                 );
            }
        }

        /// <summary>
        /// Handles the Click event of the cbTest2 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void cbTest2_Click(object sender, EventArgs e)
        {
            Helper.Test2();
        }

        /// <summary>
        /// Handles the Click event of the toolStripButton1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void toolStripButtonExecuteLambdaFilter_Click(object sender, EventArgs e)
        {
            Helper.ExecuteLambdaFilter();
        }

        /// <summary>
        /// Handles the Click event of the skriptToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void skriptToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormScript form = new FormScript(MainFormSingleton.ActivePictureBox);
            form.Show(this);
        }

        /// <summary>
        /// Handles the Click event of the cbTest3 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void cbTest3_Click(object sender, EventArgs e)
        {
            Helper.Test3();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbTest4_Click(object sender, EventArgs e)
        {
            Helper.Test4();
        }

        /// <summary>
        /// Handles the Click event of the cbTest5 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void cbTest5_Click(object sender, EventArgs e)
        {
            Helper.Test5();
        }

        /// <summary>
        /// Handles the Click event of the cbTest6 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void cbTest6_Click(object sender, EventArgs e)
        {
            Helper.Test6();
        }

        /// <summary>
        /// Handles the Click event of the editToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Handles the Click event of the localPathToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void localPathToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string sPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            FormDirectoryAcquiring form = new FormDirectoryAcquiring(sPath);
            if (form.ShowDialog() != DialogResult.OK) return;
            MainFormSingleton.ActivePictureBox.BackgroundImage = form.Image;
        }

        /// <summary>
        /// Handles the Click event of the imageInfoToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void imageInfoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Helper.ShowImageInfo();
        }

        /// <summary>
        /// Handles the Click event of the closeAllChildsToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void closeAllChildsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(closeAllChildsToolStripMenuItem, new ActionExecuteNonFilterDelegate(CloseAllChilds));
            Helper.CloseAllChilds();
        }

        /// <summary>
        /// Handles the Click event of the closeAllChildsButActiveToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void closeAllChildsButActiveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(closeAllChildsButActiveToolStripMenuItem, new ActionExecuteNonFilterDelegate(CloseAllChildsButActive));
            Helper.CloseAllChildsButActive();
        }

        /// <summary>
        /// Handles the Click event of the cbColorBlobExtractor control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void cbColorBlobExtractor_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(cbColorBlobExtractor, new ActionExecuteNonFilterDelegate(ColorBlobExtractor));
            Helper.ColorBlobExtractor();
        }

        /// <summary>
        /// Handles the Click event of the simpleBlobExtractorToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void simpleBlobExtractorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(simpleBlobExtractorToolStripMenuItem, new ActionExecuteNonFilterDelegate(SimpleBlobExtractor));
            Helper.SimpleBlobExtractor();
        }

        /// <summary>
        /// Handles the Click event of the executeFilterToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void executeFilterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            formTypeCommand = new FormTypeCommand();
            formTypeCommand.Show(this);
        }

        /// <summary>
        /// Handles the Click event of the extractAnaglyphToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void extractAnaglyphToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(extractAnaglyphToolStripMenuItem, new ActionExecuteNonFilterDelegate(ExtractAnaglyph));
            Helper.ExtractAnaglyph();
        }

        /// <summary>
        /// Handles the Click event of the open3dPicToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void open3dPicToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(open3dPicToolStripMenuItem, new ActionExecuteNonFilterDelegate(Open3dPic));
            Open3dPic();
        }

        private void Open3dPic()
        {
            Debug.WriteLine(string.Format("{0}:{1}", open3dPicToolStripMenuItem.Name, "open 3d pic"));
            FormLoad3dPic form = new FormLoad3dPic();
            if (form.ShowDialog() != DialogResult.OK) return;
            MainFormSingleton.ActivePictureBox.BackgroundImage = form.BitmapResult;
        }

        /// <summary>
        /// Handles the Click event of the disparityMapToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void disparityMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Debug.WriteLine(string.Format("{0}:{1}", disparityMapToolStripMenuItem.Name, "disparity map"));
        }

        /// <summary>
        /// Handles the Click event of the createAnaglyphToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void createAnaglyphToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Debug.WriteLine(string.Format("{0}:{1}", createAnaglyphToolStripMenuItem.Name, "create anaglyph"));
        }

        /// <summary>
        /// Handles the Click event of the convolutionToolStripMenuItem1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void convolutionToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(convolutionToolStripMenuItem1, new ActionExecuteNonFilterDelegate(CustomConvolution));
            CustomConvolution();
        }

        private void CustomConvolution()
        {
            Debug.WriteLine(string.Format("{0}:{1}", convolutionToolStripMenuItem1.Name, "convolution"));
            FormCustomConvolution formConvolution = new FormCustomConvolution();
            formConvolution.ShowDialog();
        }

        /// <summary>
        /// Handles the Click event of the analyseToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void analyseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(analyseToolStripMenuItem, new ActionExecuteNonFilterDelegate(Helper.Analyse));
            Helper.Analyse();
        }

        /// <summary>
        /// extracts the disparity map
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void extractDisparityMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(extractLeftRightJPSToolStripMenuItem, new ActionExecuteNonFilterDelegate(Helper.ExtractDisparityMap));
            Helper.ExtractDisparityMap();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void extractLeftRightJPSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(extractLeftRightJPSToolStripMenuItem, new ActionExecuteNonFilterDelegate(Helper.ExtractLeftRightJPS));
            Helper.ExtractLeftRightJPS();
        }

        /// <summary>
        /// Extract left/ride side from anaglyph
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deanaglyphToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(deanaglyphToolStripMenuItem, new ActionExecuteNonFilterDelegate(Helper.DeAnaglyph));
            Helper.DeAnaglyph();
        }

        /// <summary>
        /// Updates the filterlist
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void updateFilterlistToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(maximizeAllToolStripMenuItem, new ActionExecuteNonFilterDelegate(new VoidDelegateNonParameters(Helper.UpdateFilterList)));
            Helper.UpdateFilterList();
        }

        private void minimizeAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(maximizeAllToolStripMenuItem, new ActionExecuteNonFilterDelegate());
            Helper.SetAllMDIChildsFormWindowState(FormWindowState.Minimized);
        }

        private void maximizeAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(maximizeAllToolStripMenuItem, new ActionExecuteNonFilterDelegate(new VoidDelegateNonParameters(Helper.SetAllMDIChildsFormWindowStatemaximizeAllToolStripMenuItem(FormWindowState.Maximized))));
            Helper.SetAllMDIChildsFormWindowState(FormWindowState.Maximized);
        }

        private void normalSizeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(maximizeAllToolStripMenuItem, new ActionExecuteNonFilterDelegate());
            Helper.SetAllMDIChildsFormWindowState(FormWindowState.Normal);
        }

        private void base64FL2IBarcodeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(maximizeAllToolStripMenuItem, new ActionExecuteNonFilterDelegate(new VoidDelegateNonParameters(Helper.base64FL2IBarcode)));
            Helper.base64FL2IBarcode();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void extractLeftRightInterlacedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(extractLeftRightInterlacedToolStripMenuItem, new ActionExecuteNonFilterDelegate(Helper.ExtractLeftRightInterlaced));
            Helper.ExtractLeftRightInterlaced();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void interlacedToAnaglyphToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(nterlacedToAnaglyphToolStripMenuItem, new ActionExecuteNonFilterDelegate(Helper.InterlacedToAnaglyph));
            Helper.InterlacedToAnaglyph();
        }

        private void mode1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainFormSingleton.ActiveFormChild.ActivateTool(typeof(FloodFillTool), true);
        }

        private void imageStatisticsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //GuiHelper.SetEventHandler(imageStatisticsToolStripMenuItem, new ActionExecuteNonFilterDelegate(Helper.ImageStatistics));
            Helper.ImageStatistics();
        }

        private void copyFromActiveToAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Helper.CopyFromActiveToAll();
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            UnsafeBitmap _bitmapOld = MainFormSingleton.OriginalBitmap;
            if (_bitmapOld == null) return;

            UnsafeBitmap _bitmap = MainFormSingleton.ActivePictureBox.BackgroundImage;
            int nWidth = _bitmap.Width;
            int nHeight = _bitmap.Height;
            int x = 0;
            int y = 0;

            int nFill = (int)numericUpDown1.Value;

            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    Color color = _bitmap.GetPixel(x, y);
                    Color colorOld = _bitmapOld.GetPixel(x, y);
                    int ro = colorOld.R;
                    int go = colorOld.G;
                    int bo = colorOld.B;

                    int rn = (ro * (100 - nFill) + color.R * nFill) / 100;
                    int gn = (go * (100 - nFill) + color.G * nFill) / 100;
                    int bn = (bo * (100 - nFill) + color.B * nFill) / 100;
                    _bitmap.SetPixel(x, y, Color.FromArgb(rn, gn, bn));
                }
            }

            MainFormSingleton.ActivePictureBox.Invalidate();
            _bitmap.Dispose();
            _bitmapOld.Dispose();
        }

        private void fitToImageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Helper.SetAllWindowsToImageSize();
        }

        private void alignTopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Helper.AlignAllWindows();
        }

        private void alignFromLeftToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Helper.AlignFromLeft();
        }

        private void alignFitLeftTopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Helper.SetAllWindowsToImageSize();
            Helper.AlignAllWindows();
            Helper.AlignFromLeft();
        }

        private void fitToWidthToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Helper.SetToWidth();
        }

        private void filtersetsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExecuteFilterSet(DefaultFilterSets.WhiteColorBalanceModes);
        }

        private static void ExecuteFilterSet(FilterSet _filterSet)
        {
            Dictionary<string, FilterSet> aDictionary = new Dictionary<string, FilterSet>();

            aDictionary.Add("Improve", DefaultFilterSets.Improve);
            aDictionary.Add("Blur", DefaultFilterSets.Blur);
            //aDictionary.Add("Sharpen", DefaultFilterSets.Sharpen);
            aDictionary.Add("WhiteColorBalanceModes", DefaultFilterSets.WhiteColorBalanceModes);


            Bitmap bitmapOriginal = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
            foreach (IFilter filter in DefaultFilterSets.WhiteColorBalanceModes)
            {
                FormChild formChild = GuiHelper.CreateNewChild();
                Bitmap bitmap = (Bitmap)bitmapOriginal.Clone();
                formChild.pictureBox1.BackgroundImage = bitmap;
                filter.Execute(bitmap).Dispose();
                formChild.pictureBox1.Invalidate();
                formChild.pictureBox1.ShowFilterInfo = true;
                formChild.pictureBox1.FilterInfoText = Helper.GetInsertStatementFromFilter(filter);
            }
        }

        private void cbTest7_Click(object sender, EventArgs e)
        {
            IFilter filter = new InterpretedFilter("Normalize");

            UnsafeBitmap bitmap = MainFormSingleton.ActivePictureBox.BackgroundImage;
            filter.Execute(bitmap);
            bitmap.Dispose();

            MainFormSingleton.ActivePictureBox.Invalidate();
        }
    }
}
